package com.now.printer.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.print.PrintAttributes;
import android.provider.MediaStore;
import android.webkit.WebView;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.uttampanchasara.pdfgenerator.CreatePdf;
import com.xuexiang.xutil.tip.ToastUtils;

import org.jetbrains.annotations.NotNull;
import org.xutils.common.util.LogUtil;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class ConvertUtils {

    /**
     * //     * @param src word 文件路径
     * //     * @param desc 生成PDF的路径
     */
//    public static void convertWordToPdf(String src, String desc) {
//        try {
//            //create file inputstream object to read data from file
//            FileInputStream fs = new FileInputStream(src);
//            //create document object to wrap the file inputstream object
//            XWPFDocument doc = new XWPFDocument(fs);
//            //72 units=1 inch
//            Document pdfdoc = new Document(PageSize.A4, 72, 72, 72, 72);
//            //create a pdf writer object to write text to mypdf.pdf file
//            PdfWriter pwriter = PdfWriter.getInstance(pdfdoc, new FileOutputStream(desc));
//            //specify the vertical space between the lines of text
//            pwriter.setInitialLeading(20);
//            //get all paragraphs from word docx
//            List<XWPFParagraph> plist = doc.getParagraphs();
//            //open pdf document for writing
//            pdfdoc.open();
//            for (int i = 0; i < plist.size(); i++) {
//                //read through the list of paragraphs
//                List<XWPFRun>  xwpfRunList = plist.get(i).getRuns();
//                //get all run objects from each paragraph
//                //read through the run objects
//                for (int j = 0; j < xwpfRunList.size(); j++) {
//                    XWPFRun run = xwpfRunList.get(j);
//                    //get pictures from the run and add them to the pdf document
//                    List<XWPFPicture> piclist = run.getEmbeddedPictures();
//                    //traverse through the list and write each image to a file
//                    Iterator<XWPFPicture> iterator = piclist.iterator();
//                    while (iterator.hasNext()) {
//                        XWPFPicture pic = iterator.next();
//                        XWPFPictureData picdata = pic.getPictureData();
//                        byte[] bytepic = picdata.getData();
//                        Image imag = Image.getInstance(bytepic);
//                        pdfdoc.add(imag);
//
//                    }
//                    //get color code
//                    int color = getCode(run.getColor());
//                    //construct font object
//                    Font f = null;
//                    if (run.isBold() && run.isItalic())
//                        f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run.getFontSize(), Font.BOLDITALIC, new BaseColor(color));
//                    else if (run.isBold())
//                        f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run.getFontSize(), Font.BOLD, new BaseColor(color));
//                    else if (run.isItalic())
//                        f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run.getFontSize(), Font.ITALIC, new BaseColor(color));
//                    else if (run.isStrike())
//                        f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run.getFontSize(), Font.STRIKETHRU, new BaseColor(color));
//                    else
//                        f = FontFactory.getFont(FontFactory.TIMES_ROMAN, run.getFontSize(), Font.NORMAL, new BaseColor(color));
//                    //construct unicode string
//                    String text = run.getText(-1);
//                    byte[] bs;
//                    if (text != null) {
//                        bs = text.getBytes();
//                        String str = new String(bs, "UTF-8");
//                        //add string to the pdf document
//                        Chunk chObj1 = new Chunk(str, f);
//                        pdfdoc.add(chObj1);
//                    }
//
//                }
//                //output new line
//                pdfdoc.add(new Chunk(Chunk.NEWLINE));
//            }
//            //close pdf document
//            pdfdoc.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    public static int getCode(String code) {
        int colorCode;
        if (code != null)
            colorCode = Long.decode("0x" + code).intValue();
        else
            colorCode = Long.decode("0x000000").intValue();
        return colorCode;
    }

//    public static void convertWordToPdf(String fileUri, String outputPath) {
////        new com.aspose.slides.Aspose..License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));
//
//        try {
//            com.aspose.words.Document doc = new com.aspose.words.Document(fileUri);
//            SaveOutputParameters saveOutputParameters = doc.save(outputPath);// Save the document in PDF format.
//            String contentType = saveOutputParameters.getContentType();
////                            试下PdfSaveOptions的PageSavingCallback
//        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtil.e("as pose exception is :" + e.getMessage());
//        }
//    }

//    public static void convertExcelToPdf(String fileUri, String outputPath) {
//        try {
//            Workbook workbook = new Workbook(fileUri);
//            workbook.save(outputPath, com.aspose.cells.SaveFormat.PDF);//"E2PDFC-out.pdf"
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static void convertPptToPdf(String fileUri, String outputPath) {
////         new Aspose.Slides.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));
//        // Instantiate a Presentation object that represents a PPTX file
//        Presentation pres = new Presentation(fileUri);
//        try {
//            // Instantiate the PdfOptions class
//            PdfOptions pdfOptions = new PdfOptions();
//
//            // Set Jpeg quality
//            pdfOptions.setJpegQuality((byte) 50);
//
//            // Set behavior for metafiles
//            pdfOptions.setSaveMetafilesAsPng(true);
//
//            // Set text compression level
//            pdfOptions.setTextCompression(PdfTextCompression.Flate);
//
//            // Define the PDF standard
//
//            pdfOptions.setCompliance(PdfCompliance.PdfA1a);
//            pres.save(outputPath, SaveFormat.Pdf, pdfOptions);
//
//            pdfOptions.setCompliance(PdfCompliance.PdfA1b);
//            pres.save(outputPath, SaveFormat.Pdf, pdfOptions);
//
//            pdfOptions.setCompliance(PdfCompliance.PdfUa);
//            pres.save(outputPath, SaveFormat.Pdf, pdfOptions);
//            // Save the presentation as PDF
//        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtil.e("AsposeUtils pptConvertPdf Exception : " + e.getMessage());
//        } finally {
//            if (pres != null) pres.dispose();
//        }
//    }

    public static void convertHtmlToPdf(Context context, String htmlString) {
        String appPath = FileUtils.getCurrentAppPath(context);
        new CreatePdf(context)
                .setPdfName("printer_html")
                .openPrintDialog(false)
//                .setContentBaseUrl(webView.getUrl())
                .setPageSize(PrintAttributes.MediaSize.ISO_A4)
                .setContent(getHtmlData(htmlString))
                .setFilePath(appPath)
                .setCallbackListener(new CreatePdf.PdfCallbackListener() {
                    @Override
                    public void onFailure(@NotNull String s) {
                        // handle error
                        LogUtil.i("onFailure：" + s);

                    }

                    @Override
                    public void onSuccess(@NotNull String filePath) {
                        // do your stuff here
                        LogUtil.i("onSuccess：" + filePath);

                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                //显示dialog
                                PrinterUtils.doPrint(context, filePath);

                            }
                        }, 2000);   //5秒
                    }
                })
                .create();
    }

    /**
     * 加载html标签
     *
     * @param bodyHTML
     * @return
     */
    private static String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    /**
     * Convert text file to PDF
     *
     * @param textFilePath String
     * @param outputPath   String
     */
    public static String convertTextToPdf(String textFilePath, String outputPath) {
        FileInputStream fis = null;
        DataInputStream in = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(outputPath));
            document.open();
            File file = new File(textFilePath);
            if (file.exists()) {
                fis = new FileInputStream(file);
                in = new DataInputStream(fis);
                isr = new InputStreamReader(in);
                br = new BufferedReader(isr);
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    Paragraph para = new Paragraph(strLine + "\n");
                    para.setAlignment(Element.ALIGN_JUSTIFIED);
                    document.add(para);
                }
            } else {
                ToastUtils.toast("File " + textFilePath + " does not exist!");
            }
            document.close();
            return outputPath;
        } catch (Exception e) {
            ToastUtils.toast("An error has occurred: " + e.getMessage());
            return "";
        }
    }

    /**
     * Convert image file to PDF
     *
     * @param imagePath  String
     * @param outputPath String
     */
    @Deprecated
    public static String convertImageToPdf(String imagePath, String outputPath) {
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(outputPath));
            document.open();
            Image image = Image.getInstance(imagePath);
            document.setPageSize(PageSize.A4);
            document.addCreationDate();
            document.add(image);
            document.close();
            return outputPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void convertImageToPdf(Context context, String imagePath, String outputPath) {
        Document document = new Document(PageSize.A4, 38, 38, 50, 38);
        Rectangle documentRect = document.getPageSize();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
            document.open();
//            for (int i = 0; i < imagesUri.size(); i++) {
            Bitmap bmp = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(new File(imagePath)));
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 40, stream);
            String imageUrl = imagePath;
            imageUrl = imageUrl.replaceAll("~", "_");
            Image image = Image.getInstance(imageUrl);
            if (bmp.getWidth() > documentRect.getWidth() || bmp.getHeight() > documentRect.getHeight()) {
//                    bitmap is larger than page, so set bitmap's size similar to the whole page

//                DecimalFormat df2  = new DecimalFormat("###.00");
//                double scale = Double.parseDouble(df2.format((bmp.getWidth() / bmp.getHeight())));

                double scale = new BigDecimal((float) bmp.getWidth() / bmp.getHeight()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                LogUtil.i("图width：" + bmp.getWidth() + " 图Height：" + bmp.getHeight() + " 图的比例是 :" + scale);

                float imgWidth = documentRect.getWidth();

                float imgHeight = (float) (imgWidth / scale);
                image.scaleAbsolute(imgWidth, imgHeight);
                LogUtil.i("图很大 imgWidth : " + imgWidth + " imgHeight : " + imgHeight);

            } else {
                //bitmap is smaller than page, so add bitmap simply.
                // [note: if you want to fill page by stretching image,
                // you may set size similar to page as above]
                image.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
                LogUtil.i("图比纸小");

            }
            image.setAbsolutePosition((documentRect.getWidth() - image.getScaledWidth()) / 2, (documentRect.getHeight() - image.getScaledHeight()) / 2);
//            image.setBorder(Image.BOX);
//            image.setBorderWidth(15);
            document.add(image);
            document.newPage();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();

    }

    //多图转换，证件照
    public static void convertImageToPdf(Context context, String[] frontAndBackImagePaths, String outputPath) {
        Document document = new Document(PageSize.A4, 38, 38, 50, 38);
        Rectangle documentRect = document.getPageSize();
        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
            document.open();
            for (int i = 0; i < frontAndBackImagePaths.length; i++) {
                Bitmap bmp = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(new File(frontAndBackImagePaths[i])));
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 40, stream);
                String imageUrl = frontAndBackImagePaths[i];
                imageUrl = imageUrl.replaceAll("~", "_");
                Image image = Image.getInstance(imageUrl);
                image.scaleAbsolute(270, 175);
                image.setAlignment(Image.ALIGN_CENTER);
                document.add(new Chunk(Chunk.NEWLINE));
                document.add(new Chunk(Chunk.NEWLINE));

                for (int j = 0; j < 3; j++) {
                    Paragraph para = new Paragraph("\n");
                    para.setAlignment(Element.ALIGN_JUSTIFIED);
                    document.add(para);
                }

//                image.setAbsolutePosition(i * bmp.getWidth() + , i );
                document.add(image);
                if (i == 1) {
                    for (int j = 0; j < 3; j++) {
                        document.add(paragraph);
                    }
                }
//            document.newPage();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();

    }

    public static void convertHtmlToPdf() {
//        // step 1
//        Document document = new Document();
//        // step 2
//        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
//        // step 3
//        document.open();
//        // step 4
//        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
//        fontImp.register(FONT);
//        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
//                new FileInputStream(HTML), null, Charset.forName("UTF-8"), fontImp);
//        // step 5
//        document.close();
    }
}
